import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import IndexPage from "@/pages/IndexPage.vue";
import LayoutPage from "@/pages/LayoutPage.vue";
import ToolForum from "@/pages/ToolForum.vue";
import ToolManager from "@/pages/ToolManager.vue";
import ToolAuthor from "@/pages/ToolAuthor.vue";
import ToolPerson from "@/pages/ToolPerson.vue";
import EditPerson from "@/pages/EditPerson.vue";
import userLogin from "@/pages/UserLogin.vue";
import userRegister from "@/pages/UserRegister.vue";
import ToolInfoPage from "@/pages/ToolInfoPage.vue";
import ToolEditPage from "@/pages/ToolEditPage.vue";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/index",
  },
  {
    path: "/",
    name: "Layout",
    component: LayoutPage,
    meta: {
      topMenu: true,
      title: "枸杞工具箱",
    },
    children: [
      {
        path: "/index",
        name: "Index",
        component: IndexPage,
        meta: {
          topMenu: true,
          title: "枸杞工具箱",
        },
      },
      {
        path: "/manager",
        name: "Manager",
        component: ToolManager,
        meta: {
          topMenu: true,
          title: "枸杞工具箱",
        },
      },
      {
        path: "/forum",
        name: "Forum",
        component: ToolForum,
        meta: {
          topMenu: true,
          title: "枸杞工具箱",
        },
      },
      {
        path: "/author",
        name: "Author",
        component: ToolAuthor,
        meta: {
          topMenu: true,
          title: "枸杞工具箱",
        },
      },
      {
        path: "/person",
        name: "Person",
        component: ToolPerson,
        meta: {
          topMenu: false,
          title: "枸杞工具箱",
        },
      },
      {
        path: "/person/edit",
        name: "editPerson",
        component: EditPerson,
        meta: {
          topMenu: false,
          title: "枸杞工具箱",
        },
      },
    ],
  },
  {
    path: "/login",
    name: "Login",
    component: userLogin,
    meta: {
      topMenu: true,
      title: "枸杞工具箱",
    },
  },
  {
    path: "/register",
    name: "Register",
    component: userRegister,
    meta: {
      topMenu: true,
      title: "枸杞工具箱",
    },
  },
  {
    path: "/toolInfoPage/:id",
    name: "ToolInfo",
    component: ToolInfoPage,
    meta: {
      title: "枸杞工具箱",
    },
  },
  {
    path: "/toolEditPage/:id",
    name: "ToolEdit",
    component: ToolEditPage,
    meta: {
      title: "枸杞工具箱",
    },
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

//使用钩子函数对路由进行权限跳转
router.beforeEach((to, from, next) => {
  const role = sessionStorage.getItem("userAccount");
  // 获取标签页的标题
  document.title = `${to.meta.title}`;
  if (to.path == "/register") {
    next();
  } else if (!role && to.path !== "/login") {
    next("/login");
  } else {
    next();
  }
});

export default router;
